<template>
    <div class="app-container">
        <el-form :model="examResult" ref="form" :rules="rules" :inline="true" label-width="80px" style="width: 800px;">
            <el-form-item label="考试班级" prop="classId">
                <el-select @change="classChange" v-model="examResult.classId" clearable filterable style="width:100%">
                    <el-option v-for="item in classOptions" :label="item.className" placeholder="选择班级" :value="item.id"
                        :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="学期" prop="termId">
                <el-select v-model="examResult.termId" placeholder="请选择" style="width:250px">
                    <el-option v-for="item1 in termTimeList" :key="item1.id"
                        :label="item1.tetiBeginYear + '~' + item1.tetiEndYear" :value="item1.id">
                        <span style="float: left">{{ item1.tetiBeginYear + '~' + item1.tetiEndYear }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item1.remarks }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="考试名称" prop="examName">
                <el-input type="text" v-model="examResult.examName"></el-input>
            </el-form-item>
            <el-form-item label="描述">
                <el-input type="text" v-model="examResult.description"></el-input>
            </el-form-item>
            <el-form-item>
                <el-upload action="/" ref="upload" :headers="header" :http-request="handlerFileChange" accept=".xlsx,.xls">
                    <el-button type="primary">导入成绩</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="downExcel">导出数据</el-button>
            </el-form-item>
            <el-table :data="tableData" border>
                <el-table-column prop="id" label="" width="100" height="50" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" v-for="(column, index) in columns" :key="index" :prop="column.id"
                    :label="column.subjName">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="scope.row.subjList[index].score" />
                    </template>
                </el-table-column>

            </el-table>
            <el-form-item>
                <el-button type="primary" size="mini" @click="addResult">提交</el-button>
            </el-form-item>
        </el-form>
        <el-loading :fullscreen="true" :text="loadingText" :spinner="loadingSpinner" :background="loadingBackground"
            :lock="loadingLock" v-if="loading"></el-loading>
    </div>
</template>
  
<script>
import {
    findTeacherClassPageList,
    studentListByClass
} from "@/api/classManage/classInfo";
import { subjectListByClass } from "@/api/educational/subject.js";
import { listTermtime } from "@/api/system/termtime.js";
import {
    addExamResult,
    toExcel,
    importExcel
} from "@/api/studentInfo/examList";
import { getToken } from '@/utils/auth'
export default {
    data() {
        return {
            header: {
                'Authorization': 'Bearer ' + getToken()
            },
            tableData: [{
                index: -1,
                id: null,
                name: null,
                studentId: null,
                subjList: [
                    {
                        id: null,
                        subjCode: null,
                        subjName: null,
                        createBy: null,
                        createTime: null,
                        modifyBy: null,
                        modifyTime: null,
                        tenantId: null,
                        score: null
                    }
                ]
            }
            ],
            columns: [{
                subjList: [
                    {
                        id: null,
                        subjCode: null,
                        subjName: null,
                        createBy: null,
                        createTime: null,
                        modifyBy: null,
                        modifyTime: null,
                        tenantId: null,
                        score: null
                    }
                ]
            },
            ],
            form: {},
            classOptions: [],
            classId: 0,
            num: 1,
            termTimeList: [],
            examResult: {},
            rules: {
                termId: [{required: true, message: '请选择学期', trigger: 'blur'}],
                classId: [{required: true, message: '请选择班级', trigger: 'blur'}],
                examName: [{required: true, message: '请填写考试名称', trigger: 'blur'}]
            },
            loading: false,
            loadingText: 'Loading',
            loadingSpinner: 'el-icon-loading',
            loadingBackground: 'rgba(0, 0, 0, 0.7)',
            loadingLock: true
        };
    },
    created() {
        this.getClassList();
        this.getTermTimeList();
    },
    methods: {
        handlerFileChange(file) {
            if (this.examResult.classId == null) {
                this.$message({
                    message: '请选择班级！',
                    type: 'error'
                })
                this.$refs['upload'].clearFiles();
                return false;
            }
            if (this.examResult.termId == null) {
                this.$message({
                    message: '请选择学期！',
                    type: 'error'
                })
                this.$refs['upload'].clearFiles();
                return false;
            }
            if (this.examResult.examName == null) {
                this.$message({
                    message: '请填写考试名称！',
                    type: 'error'
                })
                this.$refs['upload'].clearFiles();
                return false;
            }
            this.examResult.studentWithSubjectVOList = this.tableData;
            let formData = new FormData();
            formData.append("file", file.file);
            formData.append("vo", JSON.stringify(this.examResult));
            // this.loading = true;
            const loading = this.$loading({
                lock: true,//lock的修改符--默认是false
                text: 'Loading',//显示在加载图标下方的加载文案
                spinner: 'el-icon-loading',//自定义加载图标类名
                background: 'rgba(0, 0, 0, 0.7)',//遮罩层颜色
                target: document.querySelector('#table')//loadin覆盖的dom元素节点
            });
            importExcel(formData).then(response => {
                loading.close();
                if (response.code == '200') {
                    this.$message({
                        message: '导入成功',
                        type: 'success'
                    })
                } else {
                    this.$message({
                        message: '导入失败',
                        type: 'error'
                    })
                }
            })
            this.$refs['upload'].clearFiles();
            this.loading = false;
        },
        downExcel() {
            this.examResult.studentWithSubjectVOList = this.tableData;
            const loading = this.$loading({
                lock: true,//lock的修改符--默认是false
                text: 'Loading',//显示在加载图标下方的加载文案
                spinner: 'el-icon-loading',//自定义加载图标类名
                background: 'rgba(0, 0, 0, 0.7)',//遮罩层颜色
                target: document.querySelector('#table')//loadin覆盖的dom元素节点
            });
            toExcel(this.examResult).then(response => {
                console.log("Excel:", response.data);
                this.downloadFile(response.data)
                loading.close();
            })
        },
        //文件导出
        downloadFile(data) {
            if (!data) {
                return
            }
            const link = document.createElement('a');
            let blob = new Blob([data], {
                type: 'application/vnd.ms-excel'
            });
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);

            link.setAttribute('download', '学生成绩表' + '.xls');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },
        classChange() {
            this.classId = this.examResult.classId;
            // this.examResult.classId = this.classId;
            this.getSubjectListByClass();
            this.getStudentListByClass();
        },
        addResult() {
            if (this.examResult.classId == null) {
                this.$message({
                    message: '请选择班级！',
                    type: 'error'
                })
                return false;
            }
            if (this.examResult.termId == null) {
                this.$message({
                    message: '请选择学期！',
                    type: 'error'
                })
                return false;
            }
            if (this.examResult.examName == null || this.examResult.examName == '') {
                this.$message({
                    message: '请填写考试名称！',
                    type: 'error'
                })
                return false;
            }
            this.examResult.studentWithSubjectVOList = this.tableData;
            // this.loading = true;
            const loading = this.$loading({
                lock: true,//lock的修改符--默认是false
                text: 'Loading',//显示在加载图标下方的加载文案
                spinner: 'el-icon-loading',//自定义加载图标类名
                background: 'rgba(0, 0, 0, 0.7)',//遮罩层颜色
                target: document.querySelector('#table')//loadin覆盖的dom元素节点
            });

            addExamResult(this.examResult).then(response => {
                this.tableData.forEach(temp => {
                    temp.subjList.forEach(temp1 => {
                        temp1.score = 0
                    })
                })
                //成功回调函数停止加载
                loading.close()
                this.$message({
                    message: '成绩录入成功',
                    type: 'success'
                });
            })
            // this.loading = false;
        },
        //查询学期
        getTermTimeList() {
            listTermtime({ pageSize: 100, pageNum: 1, status: 1 }).then(response => {
                this.termTimeList = response.data.list;
            }
            );
        },
        //查询科目
        getSubjectListByClass() {
            subjectListByClass(this.classId).then(response => {
                let columnList = []
                this.columns = []
                if (response.data) {
                    response.data.forEach(item => {
                        columnList.push({
                            id: item.id,
                            subjCode: item.subjCode,
                            subjName: item.subjName,
                            createBy: item.createBy,
                            createTime: item.createTime,
                            modifyBy: item.modifyBy,
                            modifyTime: item.modifyTime,
                            tenantId: item.tenantId,
                            score: 0
                        })
                    })
                    this.columns = Object.assign([], columnList)
                }
            });
        },
        //查询学生
        getStudentListByClass() {
            studentListByClass(this.classId).then(response => {
                let self = this;
                this.tableData.splice(0, 1);
                this.tableData = [];
                for (let index = 0; index < response.data.length; index++) {
                    this.tableData.push({
                        index: index,
                        id: response.data[index].id,
                        name: response.data[index].name,
                        studentId: response.data[index].studentId,
                        subjList: [
                            {
                                id: null,
                                subjCode: null,
                                subjName: null,
                                createBy: null,
                                createTime: null,
                                modifyBy: null,
                                modifyTime: null,
                                tenantId: null,
                                score: null
                            }
                        ]
                    })
                }
                this.tableData.forEach(temp => {
                    temp.subjList.splice(0, 1)
                })
                this.tableData.forEach(item1 => {

                    self.columns.forEach(item => {

                        item1.subjList.push(
                            {
                                id: item.id,
                                subjCode: item.subjCode,
                                subjName: item.subjName,
                                createBy: item.createBy,
                                createTime: item.createTime,
                                modifyBy: item.modifyBy,
                                modifyTime: item.modifyTime,
                                tenantId: item.tenantId,
                                score: 0
                            }
                        )
                    })
                })
            })
        },
        getClassList() {
            //查询班级
            findTeacherClassPageList({
                pageSize: 500,
                pageNum: 1,
                status: 1,
                isGraduation: 0
            }).then(resp => {
                this.classOptions = resp.data.list;
            });
        }
    }
};
</script>
  